package com.keiou.drink.util;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * 作者 ：Bob on 2017/11/7.
 * 邮箱 ：motherlovefather@126.com
 */

public class MediaHelper {

    private static MediaHelper mediaHelper;
    private MediaPlayer mMediaPlayer;

    private MediaHelper() {
        mMediaPlayer = new MediaPlayer();
    }

    public static MediaHelper getInstance() {
        if (null == mediaHelper) {
            mediaHelper = new MediaHelper();
        }
        return mediaHelper;
    }

    public void play(String path) {
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
        }

        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void playRaw(Context context, int res) {
        try {
            if (null != mMediaPlayer) {
                mMediaPlayer.reset();
            }

            mMediaPlayer = MediaPlayer.create(context, res);
            mMediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void play(Context context, int res) {
        if (null == mMediaPlayer) {
            mMediaPlayer = new MediaPlayer();
        }
        AssetFileDescriptor file = context.getResources().openRawResourceFd(res);
        mMediaPlayer.reset();
        try {
            mMediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void pause() {
        if (mMediaPlayer != null) {
            mMediaPlayer.pause();
        }
    }


    public void stop() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
        }
    }

    public void release() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }


}
